package  {
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.events.TimerEvent;
	import flash.text.TextField;
	import flash.utils.Timer;
	
	public class Found {
		
		private var elevators:Array;
		private var taskQueue:Array=new Array();
		private var timer:Timer;
		
		public function Found() { 
			//this.elevators=elevators;
			timer=new Timer(24,0);
			timer.addEventListener(TimerEvent.TIMER,outertimeIng);
			timer.start();
		}
		
		public function setElevators(elevators:Array):void
		{
			this.elevators=elevators;
		}
		
		public function addOuterTask(task:Task):void
		{
			taskQueue.push(task);	
		}
		
		public function getTaskQueue():Array
		{
			return taskQueue;
		}
		
		private function outertimeIng(e:TimerEvent):void
		{
			//outer tasks
			if(taskQueue.length)
			{
				
				for(var i:int=0;i<taskQueue.length;++i)
				{
					var upElevator:Elevator=null;
					var downElevator:Elevator=null;
					var hereElevator:Elevator=null;
					var upDiff:int=23;
					var downDiff:int=23;
					
					for(var j:int=0;j<5;++j)
					{
						if(taskQueue[i].getType()=="up" &&( (elevators[j].getFloor()<taskQueue[i].getFloor() && 
							elevators[j].getState()=="up") || elevators[j].getState()=="stop"))
						{
							var tempUpDiff=Math.abs(taskQueue[i].getFloor()-elevators[j].getFloor());
							//trace("outer!"+tempDiff);
							if(tempUpDiff<=upDiff)
							{
								upElevator=elevators[j];
								upDiff=tempUpDiff;
							}
						}
						else if(taskQueue[i].getType()=="down" && ((elevators[j].getFloor()>taskQueue[i].getFloor() &&
							 elevators[j].getState()=="down")|| elevators[j].getState()=="stop"))
						{
							var tempDownDiff=Math.abs(elevators[j].getFloor()-taskQueue[i].getFloor());
							if(tempDownDiff<=downDiff)
							{
								downElevator=elevators[j];
								downDiff=tempDownDiff;
							}
						}
						
						 if(elevators[j].getFloor()==taskQueue[i].getFloor() && elevators[j].getState()=="stop")
						 {
							 
							 hereElevator=elevators[j];
						 }
					
					}
					if(hereElevator)
					{
						trace("here!");
						taskQueue[i].setType("here");
						hereElevator.addTask(taskQueue[i]);
						taskQueue.splice(i,1);
						//var attention:TextField=
					}
					else{
					if(upElevator)
					{
						taskQueue[i].setType("up");
						upElevator.addTask(taskQueue[i]);
						trace(taskQueue[i].getFloor()+" up "+upElevator.getID());
						taskQueue.splice(i,1);
						
					}
					else if(downElevator && downElevator!=upElevator) 
					{
						taskQueue[i].setType("down");
						downElevator.addTask(taskQueue[i]);
						trace(taskQueue[i].getFloor()+" down "+downElevator.getID());
						taskQueue.splice(i,1);
					}
					}
				}
			}
		}
	
		
	}
	
}